/**
 * 营养素分类静态数据
 * 基于 database/nutrients_category.sql
 */

export interface NutrientCategory {
  category_id: number
  category_name: string
  category_level: 'major' | 'category' | 'subcategory'
  category_description: string
  parent_category_id: number | null
}

export interface NutrientInfo {
  id: number
  nutrient_name_zh: string
  nutrient_name_en: string
  unit_zh: string
  unit_en: string
  nutrient_description: string
  china_recommended_amount: string | null
  regional_adjustment: string | null
  // 解析后的推荐量范围
  recommended_min?: number
  recommended_max?: number
  recommended_target?: number
}

export interface CategoryNutrientRelation {
  category_id: number
  nutrient_id: number
}

// 营养素分类数据
export const nutrientCategories: NutrientCategory[] = [
  // 大分类
  { category_id: 1, category_name: '宏量营养素', category_level: 'major', category_description: '提供能量，如碳水4kcal/g、蛋白4kcal/g、脂9kcal/g', parent_category_id: null },
  { category_id: 2, category_name: '微量营养素', category_level: 'major', category_description: '支持代谢/免疫', parent_category_id: null },
  { category_id: 3, category_name: '其他重要膳食成分', category_level: 'major', category_description: '如水和纤维，防慢性病', parent_category_id: null },

  // 分类
  { category_id: 4, category_name: '碳水化合物', category_level: 'category', category_description: '简单 vs. 复合', parent_category_id: 1 },
  { category_id: 5, category_name: '蛋白质', category_level: 'category', category_description: '完全/不完全', parent_category_id: 1 },
  { category_id: 6, category_name: '脂肪 (脂质)', category_level: 'category', category_description: '不饱和/饱和等', parent_category_id: 1 },
  { category_id: 7, category_name: '维生素', category_level: 'category', category_description: '脂溶性/水溶性', parent_category_id: 2 },
  { category_id: 8, category_name: '矿物质', category_level: 'category', category_description: '常量/微量', parent_category_id: 2 },
  { category_id: 9, category_name: '水', category_level: 'category', category_description: '占体重的60%，维持体液/温度', parent_category_id: 3 },
  { category_id: 10, category_name: '膳食纤维', category_level: 'category', category_description: '可溶/不可溶', parent_category_id: 3 },

  // 子分类
  { category_id: 11, category_name: '简单碳水化合物 (糖)', category_level: 'subcategory', category_description: '总糖<50g（<总能量10%）', parent_category_id: 4 },
  { category_id: 12, category_name: '复合碳水化合物', category_level: 'subcategory', category_description: '250-400g（总能量50-65%）', parent_category_id: 4 },
  { category_id: 13, category_name: '完全蛋白质', category_level: 'subcategory', category_description: '60-70g（总能量10-20%）', parent_category_id: 5 },
  { category_id: 14, category_name: '不完全蛋白质', category_level: 'subcategory', category_description: '缺某些必需氨基酸，可互补', parent_category_id: 5 },
  { category_id: 15, category_name: '不饱和脂肪', category_level: 'subcategory', category_description: '总脂20-30%；Omega-3 1.6-2g', parent_category_id: 6 },
  { category_id: 16, category_name: '饱和脂肪', category_level: 'subcategory', category_description: '<总能量10%', parent_category_id: 6 },
  { category_id: 17, category_name: '反式脂肪', category_level: 'subcategory', category_description: '<总能量1%', parent_category_id: 6 },
  { category_id: 18, category_name: '其他脂质', category_level: 'subcategory', category_description: '胆固醇<300mg', parent_category_id: 6 },
  { category_id: 19, category_name: '脂溶性维生素', category_level: 'subcategory', category_description: 'A:700-800μg；D:10-20μg；E:14mg', parent_category_id: 7 },
  { category_id: 20, category_name: '水溶性维生素', category_level: 'subcategory', category_description: 'C:100mg；B1:1.4mg', parent_category_id: 7 },
  { category_id: 21, category_name: '常量元素', category_level: 'subcategory', category_description: '钙:800-1000mg', parent_category_id: 8 },
  { category_id: 22, category_name: '微量元素', category_level: 'subcategory', category_description: '铁:12-15mg', parent_category_id: 8 },
  { category_id: 23, category_name: '可溶性纤维', category_level: 'subcategory', category_description: '总纤维25-30g', parent_category_id: 10 },
]

// 营养素数据
export const nutrients: NutrientInfo[] = [
  { id: 1, nutrient_name_zh: '能量', nutrient_name_en: 'Energy', unit_zh: '千卡/100克', unit_en: 'kcal/100g', nutrient_description: '提供热量，宏量营养素总和', china_recommended_amount: '男1800-2200kcal/日，女1600-2000kcal/日', regional_adjustment: '2023版下调10-15%，因久坐增多' },
  { id: 2, nutrient_name_zh: '蛋白质', nutrient_name_en: 'Protein', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '构建组织，含必需氨基酸', china_recommended_amount: '60-70g（总能量10-20%）', regional_adjustment: '鼓励鱼虾、蛋奶、瘦肉；豆类互补植物蛋白' },
  { id: 3, nutrient_name_zh: '脂肪', nutrient_name_en: 'Fat', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '提供能量，细胞膜成分', china_recommended_amount: '总脂20-30%', regional_adjustment: '优先植物油，限饱和/反式' },
  { id: 4, nutrient_name_zh: 'Omega-3', nutrient_name_en: 'Omega-3', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '多不饱和脂肪酸，支持心脑健康', china_recommended_amount: '1.6-2g', regional_adjustment: '增加深海鱼摄入补Omega-3' },
  { id: 5, nutrient_name_zh: '碳水化合物', nutrient_name_en: 'Carbohydrate', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '主要能量来源', china_recommended_amount: '250-400g（总能量50-65%）', regional_adjustment: '以谷薯类为主，限简单糖' },
  { id: 6, nutrient_name_zh: '糖', nutrient_name_en: 'Sugars', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '简单碳水化合物，提供快速能量', china_recommended_amount: '总糖<50g（<总能量10%）', regional_adjustment: '强调限加糖饮料，适应中国茶饮文化' },
  { id: 7, nutrient_name_zh: '抗性淀粉', nutrient_name_en: 'Resistant Starch', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '类似纤维，促进肠道健康', china_recommended_amount: null, regional_adjustment: null },
  { id: 8, nutrient_name_zh: '膳食纤维', nutrient_name_en: 'Dietary Fiber', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '促进肠道健康，防慢性病', china_recommended_amount: '25-30g', regional_adjustment: '从全谷、果蔬获取；防便秘/糖尿病' },
  { id: 9, nutrient_name_zh: '钠', nutrient_name_en: 'Sodium', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '体液平衡', china_recommended_amount: '<2000mg（盐<5g）', regional_adjustment: '控钠防高血压（中国高盐饮食）' },
  { id: 10, nutrient_name_zh: '镁', nutrient_name_en: 'Magnesium', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '酶激活', china_recommended_amount: '330-370mg', regional_adjustment: '从食物补' },
  { id: 11, nutrient_name_zh: '钙', nutrient_name_en: 'Calcium', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '骨骼健康', china_recommended_amount: '800-1000mg', regional_adjustment: '从奶/豆腐补，控钠防高血压' },
  { id: 12, nutrient_name_zh: '铁', nutrient_name_en: 'Iron', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '血红蛋白', china_recommended_amount: '12-15mg（女更高）', regional_adjustment: '从动物源补（女性缺铁多）' },
  { id: 13, nutrient_name_zh: '锌', nutrient_name_en: 'Zinc', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '免疫支持', china_recommended_amount: '12.5mg', regional_adjustment: '从动物源补' },
  { id: 14, nutrient_name_zh: '硒', nutrient_name_en: 'Selenium', unit_zh: '微克/100克', unit_en: 'mcg/100g', nutrient_description: '抗氧化', china_recommended_amount: '50-60μg', regional_adjustment: '针对区域补' },
  { id: 15, nutrient_name_zh: '维生素A', nutrient_name_en: 'Vitamin A', unit_zh: '微克/100克', unit_en: 'μg/100g', nutrient_description: '视网膜健康', china_recommended_amount: '700-800μg', regional_adjustment: '从绿叶菜获取，适应中国蔬菜丰富' },
  { id: 16, nutrient_name_zh: '维生素C', nutrient_name_en: 'Vitamin C', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '抗坏血酸，免疫支持', china_recommended_amount: '100mg', regional_adjustment: '从新鲜蔬果补' },
  { id: 17, nutrient_name_zh: '维生素D', nutrient_name_en: 'Vitamin D', unit_zh: '微克/100克', unit_en: 'mcg/100g', nutrient_description: '骨骼健康', china_recommended_amount: '10-20μg', regional_adjustment: '加强D补充（室内活动多）' },
  { id: 18, nutrient_name_zh: '维生素E', nutrient_name_en: 'Vitamin E', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '抗氧化', china_recommended_amount: '14mg', regional_adjustment: '加强补充' },
  { id: 19, nutrient_name_zh: '维生素B1', nutrient_name_en: 'Thiamin', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '硫胺素，能量代谢', china_recommended_amount: '1.4mg', regional_adjustment: 'B族从全谷、豆类补' },
  { id: 20, nutrient_name_zh: '维生素B2', nutrient_name_en: 'Riboflavin', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '核黄素，能量代谢', china_recommended_amount: '1.4mg', regional_adjustment: 'B族从全谷、豆类补' },
  { id: 21, nutrient_name_zh: '维生素B6', nutrient_name_en: 'Vitamin B6', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '吡哆醇，能量代谢', china_recommended_amount: '1.4mg', regional_adjustment: 'B族从全谷、豆类补' },
  { id: 22, nutrient_name_zh: '维生素B12', nutrient_name_en: 'Vitamin B12', unit_zh: '微克/100克', unit_en: 'mcg/100g', nutrient_description: '钴胺素，神经健康', china_recommended_amount: '2.4μg', regional_adjustment: '孕妇补，vegan需补充' },
  { id: 23, nutrient_name_zh: '烟酸', nutrient_name_en: 'Niacin', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '维生素B3，能量代谢', china_recommended_amount: '14mg', regional_adjustment: 'B族从全谷、豆类补' },
  { id: 24, nutrient_name_zh: '叶酸', nutrient_name_en: 'Folate', unit_zh: '微克/100克', unit_en: 'mcg/100g', nutrient_description: '维生素B9，防神经管缺陷', china_recommended_amount: '400μg', regional_adjustment: '孕妇叶酸400μg' },
  { id: 25, nutrient_name_zh: '泛酸', nutrient_name_en: 'Pantothenic Acid', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '维生素B5，能量代谢', china_recommended_amount: null, regional_adjustment: 'B族从全谷、豆类补' },
  { id: 26, nutrient_name_zh: '牛磺酸', nutrient_name_en: 'Taurine', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '支持神经和心血管', china_recommended_amount: null, regional_adjustment: null },
  { id: 27, nutrient_name_zh: '胆固醇', nutrient_name_en: 'Cholesterol', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '细胞膜成分，过高风险心血管', china_recommended_amount: '<300mg', regional_adjustment: '减少肥肉、加工肉' },
  { id: 28, nutrient_name_zh: '灰分', nutrient_name_en: 'Ash', unit_zh: '克/100克', unit_en: 'g/100g', nutrient_description: '矿物质残留', china_recommended_amount: null, regional_adjustment: null },
  { id: 29, nutrient_name_zh: '磷', nutrient_name_en: 'Phosphorus', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '骨/ATP成分', china_recommended_amount: '700mg', regional_adjustment: '从食物平衡摄入' },
  { id: 30, nutrient_name_zh: '钾', nutrient_name_en: 'Potassium', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '心律调节', china_recommended_amount: '2000mg', regional_adjustment: '从蔬果补' },
  { id: 31, nutrient_name_zh: '铜', nutrient_name_en: 'Copper', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '铁吸收', china_recommended_amount: null, regional_adjustment: null },
  { id: 32, nutrient_name_zh: '锰', nutrient_name_en: 'Manganese', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '骨代谢', china_recommended_amount: null, regional_adjustment: null },
  { id: 33, nutrient_name_zh: '碘', nutrient_name_en: 'Iodine', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '甲状腺健康', china_recommended_amount: '120μg', regional_adjustment: '用碘盐，针对内陆缺碘区' },
  { id: 34, nutrient_name_zh: '胡萝卜素', nutrient_name_en: 'Carotene', unit_zh: '微克/100克', unit_en: 'μg/100g', nutrient_description: '维生素A前体', china_recommended_amount: null, regional_adjustment: '从绿叶菜获取' },
  { id: 35, nutrient_name_zh: '视黄醇', nutrient_name_en: 'Retinol', unit_zh: '微克/100克', unit_en: 'μg/100g', nutrient_description: '维生素A形式', china_recommended_amount: null, regional_adjustment: null },
  { id: 36, nutrient_name_zh: '嘌呤', nutrient_name_en: 'Purine', unit_zh: '毫克/100克', unit_en: 'mg/100g', nutrient_description: '代谢产物，高尿酸风险', china_recommended_amount: null, regional_adjustment: null },
]

// 分类-营养素关系
export const categoryNutrientRelations: CategoryNutrientRelation[] = [
  // 子分类关联（最精确的分类）
  { category_id: 11, nutrient_id: 6 },  // 糖 -> 简单碳水化合物
  { category_id: 12, nutrient_id: 5 },  // 碳水化合物 -> 复合碳水化合物
  { category_id: 12, nutrient_id: 7 },  // 抗性淀粉 -> 复合碳水化合物
  { category_id: 13, nutrient_id: 2 },  // 蛋白质 -> 完全蛋白质
  { category_id: 14, nutrient_id: 2 },  // 蛋白质 -> 不完全蛋白质
  { category_id: 15, nutrient_id: 4 },  // Omega-3 -> 不饱和脂肪
  { category_id: 16, nutrient_id: 3 },  // 脂肪 -> 饱和脂肪
  { category_id: 17, nutrient_id: 3 },  // 脂肪 -> 反式脂肪
  { category_id: 18, nutrient_id: 27 }, // 胆固醇 -> 其他脂质
  { category_id: 19, nutrient_id: 15 }, // 维生素A -> 脂溶性维生素
  { category_id: 19, nutrient_id: 17 }, // 维生素D -> 脂溶性维生素
  { category_id: 19, nutrient_id: 18 }, // 维生素E -> 脂溶性维生素
  { category_id: 19, nutrient_id: 34 }, // 胡萝卜素 -> 脂溶性维生素
  { category_id: 19, nutrient_id: 35 }, // 视黄醇 -> 脂溶性维生素
  { category_id: 20, nutrient_id: 16 }, // 维生素C -> 水溶性维生素
  { category_id: 20, nutrient_id: 19 }, // 维生素B1 -> 水溶性维生素
  { category_id: 20, nutrient_id: 20 }, // 维生素B2 -> 水溶性维生素
  { category_id: 20, nutrient_id: 21 }, // 维生素B6 -> 水溶性维生素
  { category_id: 20, nutrient_id: 22 }, // 维生素B12 -> 水溶性维生素
  { category_id: 20, nutrient_id: 23 }, // 烟酸(B3) -> 水溶性维生素
  { category_id: 20, nutrient_id: 24 }, // 叶酸(B9) -> 水溶性维生素
  { category_id: 20, nutrient_id: 25 }, // 泛酸(B5) -> 水溶性维生素
  { category_id: 21, nutrient_id: 11 }, // 钙 -> 常量元素
  { category_id: 21, nutrient_id: 29 }, // 磷 -> 常量元素
  { category_id: 21, nutrient_id: 30 }, // 钾 -> 常量元素
  { category_id: 21, nutrient_id: 9 },  // 钠 -> 常量元素
  { category_id: 21, nutrient_id: 10 }, // 镁 -> 常量元素
  { category_id: 22, nutrient_id: 12 }, // 铁 -> 微量元素
  { category_id: 22, nutrient_id: 13 }, // 锌 -> 微量元素
  { category_id: 22, nutrient_id: 33 }, // 碘 -> 微量元素
  { category_id: 22, nutrient_id: 14 }, // 硒 -> 微量元素
  { category_id: 22, nutrient_id: 31 }, // 铜 -> 微量元素
  { category_id: 22, nutrient_id: 32 }, // 锰 -> 微量元素
  { category_id: 23, nutrient_id: 8 },  // 膳食纤维 -> 可溶性纤维

  // 中间层（分类）关联 - 聚合子分类的营养素
  { category_id: 4, nutrient_id: 5 },   // 碳水化合物 -> 碳水化合物分类
  { category_id: 4, nutrient_id: 6 },   // 糖 -> 碳水化合物分类
  { category_id: 4, nutrient_id: 7 },   // 抗性淀粉 -> 碳水化合物分类
  { category_id: 5, nutrient_id: 2 },   // 蛋白质 -> 蛋白质分类
  { category_id: 6, nutrient_id: 3 },   // 脂肪 -> 脂肪分类
  { category_id: 6, nutrient_id: 4 },   // Omega-3 -> 脂肪分类
  { category_id: 6, nutrient_id: 27 },  // 胆固醇 -> 脂肪分类
  { category_id: 7, nutrient_id: 15 },  // 维生素A -> 维生素分类
  { category_id: 7, nutrient_id: 16 },  // 维生素C -> 维生素分类
  { category_id: 7, nutrient_id: 17 },  // 维生素D -> 维生素分类
  { category_id: 7, nutrient_id: 18 },  // 维生素E -> 维生素分类
  { category_id: 7, nutrient_id: 19 },  // 维生素B1 -> 维生素分类
  { category_id: 7, nutrient_id: 20 },  // 维生素B2 -> 维生素分类
  { category_id: 7, nutrient_id: 21 },  // 维生素B6 -> 维生素分类
  { category_id: 7, nutrient_id: 22 },  // 维生素B12 -> 维生素分类
  { category_id: 7, nutrient_id: 23 },  // 烟酸 -> 维生素分类
  { category_id: 7, nutrient_id: 24 },  // 叶酸 -> 维生素分类
  { category_id: 7, nutrient_id: 25 },  // 泛酸 -> 维生素分类
  { category_id: 7, nutrient_id: 34 },  // 胡萝卜素 -> 维生素分类
  { category_id: 7, nutrient_id: 35 },  // 视黄醇 -> 维生素分类
  { category_id: 8, nutrient_id: 9 },   // 钠 -> 矿物质分类
  { category_id: 8, nutrient_id: 10 },  // 镁 -> 矿物质分类
  { category_id: 8, nutrient_id: 11 },  // 钙 -> 矿物质分类
  { category_id: 8, nutrient_id: 12 },  // 铁 -> 矿物质分类
  { category_id: 8, nutrient_id: 13 },  // 锌 -> 矿物质分类
  { category_id: 8, nutrient_id: 14 },  // 硒 -> 矿物质分类
  { category_id: 8, nutrient_id: 29 },  // 磷 -> 矿物质分类
  { category_id: 8, nutrient_id: 30 },  // 钾 -> 矿物质分类
  { category_id: 8, nutrient_id: 31 },  // 铜 -> 矿物质分类
  { category_id: 8, nutrient_id: 32 },  // 锰 -> 矿物质分类
  { category_id: 8, nutrient_id: 33 },  // 碘 -> 矿物质分类
  // 注意：category_id 9 (水) 在当前数据中没有对应的营养素字段
  { category_id: 10, nutrient_id: 8 },  // 膳食纤维 -> 膳食纤维分类

  // 大分类直接关联（无精确子分类的营养素）
  { category_id: 1, nutrient_id: 1 },   // 能量 -> 宏量营养素
  { category_id: 1, nutrient_id: 36 },  // 嘌呤 -> 宏量营养素
  { category_id: 2, nutrient_id: 26 },  // 牛磺酸 -> 微量营养素
  { category_id: 2, nutrient_id: 28 },  // 灰分 -> 微量营养素
]

/**
 * 获取营养素所属的大分类
 */
export function getNutrientMajorCategory(nutrientNameEn: string): NutrientCategory | null {
  // 营养素英文名到ID的映射
  const nutrientMap: Record<string, number> = {
    'Energy': 1,
    'Protein': 2,
    'Fat': 3,
    'Omega-3': 4,
    'Carbohydrate': 5,
    'Sugars': 6,
    'Resistant Starch': 7,
    'Dietary Fiber': 8,
    'Sodium': 9,
    'Magnesium': 10,
    'Calcium': 11,
    'Iron': 12,
    'Zinc': 13,
    'Selenium': 14,
    'Vitamin A': 15,
    'Vitamin C': 16,
    'Vitamin D': 17,
    'Vitamin E': 18,
    'Thiamin': 19,
    'Riboflavin': 20,
    'Vitamin B6': 21,
    'Vitamin B12': 22,
    'Niacin': 23,
    'Folate': 24,
    'Pantothenic Acid': 25,
    'Taurine': 26,
    'Cholesterol': 27,
    'Ash': 28,
    'Phosphorus': 29,
    'Potassium': 30,
    'Copper': 31,
    'Manganese': 32,
    'Iodine': 33,
    'Carotene': 34,
    'Retinol': 35,
    'Purine': 36,
  }
  
  const nutrientId = nutrientMap[nutrientNameEn]
  if (!nutrientId) return null
  
  // 查找营养素所属的大分类
  const relation = categoryNutrientRelations.find(r => r.nutrient_id === nutrientId)
  if (!relation) return null
  
  // 获取大分类（category_id 1, 2, 3）
  const majorCategories = nutrientCategories.filter(c => c.category_level === 'major')
  return majorCategories.find(c => c.category_id === relation.category_id) || null
}

/**
 * 按大分类分组营养素字段
 */
export interface NutrientFieldGroup {
  majorCategory: NutrientCategory
  fields: Array<{
    key: string
    label: string
    unit: string
    nutrientId: number
  }>
}

/**
 * 获取食物营养素字段的分类分组
 */
export function getNutrientFieldGroups(): NutrientFieldGroup[] {
  const groups: NutrientFieldGroup[] = []
  
  // 宏量营养素
  const macroCategory = nutrientCategories.find(c => c.category_id === 1)!
  groups.push({
    majorCategory: macroCategory,
    fields: [
      { key: 'energy_kcal', label: '能量', unit: 'kcal', nutrientId: 1 },
      { key: 'protein_g', label: '蛋白质', unit: 'g', nutrientId: 2 },
      { key: 'fat_g', label: '脂肪', unit: 'g', nutrientId: 3 },
      { key: 'omega3_g', label: 'Omega-3', unit: 'g', nutrientId: 4 },
      { key: 'carb_g', label: '碳水化合物', unit: 'g', nutrientId: 5 },
      { key: 'sugars_g', label: '糖', unit: 'g', nutrientId: 6 },
      { key: 'resistant_starch_g', label: '抗性淀粉', unit: 'g', nutrientId: 7 },
      { key: 'cholesterol_mg', label: '胆固醇', unit: 'mg', nutrientId: 27 },
      { key: 'purine_mg', label: '嘌呤', unit: 'mg', nutrientId: 36 },
    ]
  })
  
  // 微量营养素
  const microCategory = nutrientCategories.find(c => c.category_id === 2)!
  groups.push({
    majorCategory: microCategory,
    fields: [
      { key: 'vitamin_a_ug', label: '维生素A', unit: 'μg', nutrientId: 15 },
      { key: 'vitamin_c_mg', label: '维生素C', unit: 'mg', nutrientId: 16 },
      { key: 'vitamin_d_mcg', label: '维生素D', unit: 'μg', nutrientId: 17 },
      { key: 'vitamin_e_mg', label: '维生素E', unit: 'mg', nutrientId: 18 },
      { key: 'thiamin_mg', label: '维生素B1', unit: 'mg', nutrientId: 19 },
      { key: 'riboflavin_mg', label: '维生素B2', unit: 'mg', nutrientId: 20 },
      { key: 'vitamin_b6_mg', label: '维生素B6', unit: 'mg', nutrientId: 21 },
      { key: 'vitamin_b12_mcg', label: '维生素B12', unit: 'μg', nutrientId: 22 },
      { key: 'niacin_mg', label: '烟酸', unit: 'mg', nutrientId: 23 },
      { key: 'folate_mcg', label: '叶酸', unit: 'μg', nutrientId: 24 },
      { key: 'pantothenic_acid_mg', label: '泛酸', unit: 'mg', nutrientId: 25 },
      { key: 'sodium_mg', label: '钠', unit: 'mg', nutrientId: 9 },
      { key: 'magnesium_mg', label: '镁', unit: 'mg', nutrientId: 10 },
      { key: 'calcium_mg', label: '钙', unit: 'mg', nutrientId: 11 },
      { key: 'iron_mg', label: '铁', unit: 'mg', nutrientId: 12 },
      { key: 'zinc_mg', label: '锌', unit: 'mg', nutrientId: 13 },
      { key: 'selenium_mcg', label: '硒', unit: 'μg', nutrientId: 14 },
      { key: 'phosphorus_mg', label: '磷', unit: 'mg', nutrientId: 29 },
      { key: 'potassium_mg', label: '钾', unit: 'mg', nutrientId: 30 },
      { key: 'copper_mg', label: '铜', unit: 'mg', nutrientId: 31 },
      { key: 'manganese_mg', label: '锰', unit: 'mg', nutrientId: 32 },
      { key: 'iodine_mg', label: '碘', unit: 'mg', nutrientId: 33 },
      { key: 'carotene_ug', label: '胡萝卜素', unit: 'μg', nutrientId: 34 },
      { key: 'retinol_ug', label: '视黄醇', unit: 'μg', nutrientId: 35 },
      { key: 'taurine_mg', label: '牛磺酸', unit: 'mg', nutrientId: 26 },
      { key: 'ash_g', label: '灰分', unit: 'g', nutrientId: 28 },
    ]
  })
  
  // 其他重要膳食成分
  const otherCategory = nutrientCategories.find(c => c.category_id === 3)!
  groups.push({
    majorCategory: otherCategory,
    fields: [
      { key: 'fiber_g', label: '膳食纤维', unit: 'g', nutrientId: 8 },
    ]
  })
  
  return groups
}

/**
 * 解析推荐摄入量字符串
 * 支持格式：
 * - "800-1000mg" -> { min: 800, max: 1000 }
 * - "<2000mg" -> { max: 2000 }
 * - "100mg" -> { target: 100 }
 * - "男1800-2200kcal/日，女1600-2000kcal/日" -> { min: 1600, max: 2200 }
 */
export function parseRecommendedAmount(amountStr: string | null): {
  min?: number
  max?: number
  target?: number
} {
  if (!amountStr) return {}

  // 移除单位和空格
  const cleaned = amountStr.replace(/[a-zA-Zμ\/日，；、]/g, '').trim()

  // 匹配范围格式：800-1000 或 男1800-2200女1600-2000
  const rangeMatch = cleaned.match(/(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)/g)
  if (rangeMatch && rangeMatch.length > 0) {
    // 提取所有数字
    const numbers = rangeMatch.flatMap(range => {
      const [min, max] = range.split('-').map(Number)
      return [min, max]
    })
    return {
      min: Math.min(...numbers),
      max: Math.max(...numbers)
    }
  }

  // 匹配小于格式：<2000
  const lessThanMatch = cleaned.match(/<(\d+(?:\.\d+)?)/)
  if (lessThanMatch) {
    return { max: Number(lessThanMatch[1]) }
  }

  // 匹配大于格式：>50
  const greaterThanMatch = cleaned.match(/>(\d+(?:\.\d+)?)/)
  if (greaterThanMatch) {
    return { min: Number(greaterThanMatch[1]) }
  }

  // 匹配单个数字
  const singleMatch = cleaned.match(/(\d+(?:\.\d+)?)/)
  if (singleMatch) {
    return { target: Number(singleMatch[1]) }
  }

  return {}
}

/**
 * 获取营养素的推荐摄入量信息
 */
export function getNutrientRecommendation(nutrientId: number) {
  const nutrient = nutrients.find(n => n.id === nutrientId)
  if (!nutrient) return null

  const parsed = parseRecommendedAmount(nutrient.china_recommended_amount)

  return {
    ...nutrient,
    ...parsed
  }
}

/**
 * 计算营养素充足度（百分比）
 * @param intake 实际摄入量
 * @param nutrientId 营养素ID
 * @returns 充足度百分比，如果没有推荐量则返回null
 */
export function calculateNutrientAdequacy(intake: number, nutrientId: number): number | null {
  const recommendation = getNutrientRecommendation(nutrientId)
  if (!recommendation) return null

  let referenceValue: number

  if (recommendation.target !== undefined) {
    referenceValue = recommendation.target
  } else if (recommendation.min !== undefined && recommendation.max !== undefined) {
    // 使用范围的中间值作为参考
    referenceValue = (recommendation.min + recommendation.max) / 2
  } else if (recommendation.max !== undefined) {
    // 如果只有最大值（如钠<2000mg），使用最大值作为参考
    referenceValue = recommendation.max
  } else if (recommendation.min !== undefined) {
    // 如果只有最小值，使用最小值作为参考
    referenceValue = recommendation.min
  } else {
    return null
  }

  return (intake / referenceValue) * 100
}

/**
 * 评估营养素摄入状态
 * @param intake 实际摄入量
 * @param nutrientId 营养素ID
 * @returns 状态：'insufficient'(不足) | 'adequate'(达标) | 'excessive'(过量) | 'unknown'(未知)
 */
export function evaluateNutrientStatus(
  intake: number,
  nutrientId: number
): 'insufficient' | 'adequate' | 'excessive' | 'unknown' {
  const recommendation = getNutrientRecommendation(nutrientId)
  if (!recommendation) return 'unknown'

  // 对于有最大值限制的营养素（如钠、糖），超过最大值为过量
  if (recommendation.max !== undefined && recommendation.min === undefined) {
    if (intake > recommendation.max * 1.2) return 'excessive'
    if (intake <= recommendation.max) return 'adequate'
    return 'excessive'
  }

  // 对于有范围的营养素
  if (recommendation.min !== undefined && recommendation.max !== undefined) {
    if (intake < recommendation.min * 0.8) return 'insufficient'
    if (intake > recommendation.max * 1.2) return 'excessive'
    return 'adequate'
  }

  // 对于有目标值的营养素
  if (recommendation.target !== undefined) {
    if (intake < recommendation.target * 0.8) return 'insufficient'
    if (intake > recommendation.target * 1.2) return 'excessive'
    return 'adequate'
  }

  return 'unknown'
}

